<?php


namespace PKFrame\Lib;
defined('PATH_PK') or die();


use PKFrame\Lib\Cache\Local;
use PKFrame\Lib\Cache\Tmp;

class Cache
{

    private static $instance;
    private static $local;
    private static $tmp;
    private static $redis;

    /**
     * @return Cache
     */
    public static function getInstance(): Cache
    {
        if (is_null(static::$instance)) {
            static::$instance = new static;
        }

        return self::$instance;
    }

    /**
     * @return Local
     */
    public function Disk(): Local
    {
        if (is_null(static::$local)) {
            static::$local = new Local();
        }

        return self::$local;
    }

    /**
     * @return Tmp
     */
    public function Tmp(): Tmp
    {
        if (is_null(static::$tmp)) {
            static::$tmp = new Tmp();
        }

        return self::$tmp;
    }

    public function Redis(int $index_link = 0): \Redis
    {
        static $redis;
        if (empty($redis) || !array_key_exists($index_link, $redis)) {
            $config = $this->getRedisConfig($index_link);
            $redis[$index_link] = new \Redis();
            $redis[$index_link]->connect($config['host'], $config['port']);
            empty($config['pass']) ?: $redis[$index_link]->auth($config['pass']);
            $redis[$index_link]->select($config['db']);
        }
        return $redis[$index_link];
    }

    protected function getRedisConfig($index_link = 0): array
    {
        $configList = cache()->Disk()->ReadByConfig('Redis');
        $nowConfig = [];
        try {
            if (empty($configList) || !is_array($configList)) {
                throw new \Exception(language('Redis_ConfigEmpty'));
            } else if (array_key_exists($index_link, $configList)) {
                $nowConfig = $configList[$index_link];
            } else {
                throw new \Exception(language('Redis_ConfigEmpty'));
            }
        } catch (\Exception $exception) {
            out()->notice($exception->getMessage());
        }
        return $nowConfig;
    }

}